/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */




(function() {
    //
    // Menu theme.
    //
    var initialPageLoadURL = window.location.pathname;
    var freshDomContentLoaded = true; 
    var browserURLRewriteSupported = false;
    var contentSection = $('.content');
    var notificationSection = $('.appNotifcation'); 
    if (history.pushState) {
        browserURLRewriteSupported = true;
    }

    $(".mainMenu .link a").bind("click touch", function(e) {
        if (browserURLRewriteSupported) {
            e.preventDefault();
        }
    });

    $(".mainMenu .link").bind("click touch", function(e) {
        e.preventDefault();
        if (reloadTimer != null) {
            window.clearTimeout(reloadTimer);
            reloadTimer = null;
        }
        abm.utils.log("Menu click/touch default prevented");
        var anchor = $(this).find("a");
        loadContentWithAjax(anchor.attr("href"));
    });

    //
    // Function to handle the back button
    //
    $(window).bind("popstate", function(e) {
        //
        // If Page is getting loaded initially and popstate event is getting fired on page load. Diregard the event.
        //
        if (initialPageLoadURL === window.location.pathname && freshDomContentLoaded)
            return;
        else{
        	freshDomContentLoaded = false;
        	console.log(window.location.pathname);
        	loadContentWithAjax(window.location.pathname, true);
        }
    });
    var reloadTimer;

    function loadContentWithAjax(URL,backButtonLoading) {
        showHideSpinner();
        var givenURL = URL || window.location.pathname;
        backButtonLoading = backButtonLoading || false;
        targetURL = givenURL + "?" + abm.data.ajaxParamName + "=" + abm.data.ajaxParamContentValue;
        abm.utils.log("Loading contents from  : " + targetURL);
        contentSection.load(targetURL, function(response, status, xhr) {
            if (status == "error") {
                switch (xhr.staus) {
                    case 404:
                    case 500:
                        $(this).html(response);
                        break;
                    default:
                        abm.utils.log("Error detected : " + status + " , " + xhr + " , " + response);
                        retryLoadingContent(this, URL, 5);
                }
            } else {
            	if(backButtonLoading == false){
            		window.history.pushState("ABM New URL Loaded", "Test", givenURL);	
            	}
                error = false;
                window.clearTimeout(reloadTimer);
                reloadTimer = null;
            }
            showHideSpinner();
        });
    }
    var spinnerContent = null;

    function retryLoadingContent(content, URL, seconds) {
        if (seconds == 0) {
            loadContentWithAjax(URL);
        } else {
        	showMessage("We are facing difficulties retrieving the data . . . We shall retry in " + seconds + " seconds.");
            reloadTimer = setTimeout(function() {
                retryLoadingContent(content, URL, seconds - 1);
            }, 1000);
        }
    }
    
    function prepareSpinnerContent() {
        if ($(".spinner").length > 0) {
            spinnerContent = $("<div />").append($(".spinner").clone()).html();
            abm.utils.log("Spinner Content : " + spinnerContent);
            $(".spinner").remove();
        }
    }

    function showHideSpinner() {
        if ($(".spinner").length === 0) {
            $("body").prepend(spinnerContent);
            var spinDiv = $(".spinner .container");
            var messageDiv = $(".spinner .message")
            var spinDivMarginTop = (abm.utils.currentViewPort.height - spinDiv.height()) / 2;
            spinDiv.css("margin-top", spinDivMarginTop + "px");
        } else {
            $(".spinner").fadeOut(300, function() {
                $(this).remove();
            });
        }
    }
    
    
    function showMessage(message){
    	var appNotification = $('.appNotifcation p');
    	if (appNotification.length == 0){
    	    	$('body').prepend("<aside class=\"appNotifcation\"><p>"+message+"</p></aside>");
    	}else{
    		appNotification.text(message);
    	}
    }
    
    function hideMessage(){
    	$('.appNotifcation').remove();
    }
    

    $("document").ready(function() {
        prepareSpinnerContent();
    });
}
)();